package utils

import (
	"clouds.lgb24kcs.cn/global"
	"crypto/aes"
	"encoding/base64"
	"golang.org/x/crypto/bcrypt"
	"log"
)

func GenerateFromPassword(password []byte) (string, error) {
	b, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	if err != nil {
		global.APP.Log.Error(err.Error())

		return "", err
	}
	return string(b), nil
}

func CompareHashAndPassword(hashedPassword, password []byte) bool {
	if err := bcrypt.CompareHashAndPassword(hashedPassword, password); err != nil {
		global.APP.Log.Error(err.Error())

		return false
	}
	return true
}

func DecryptAES(key []byte, ct string) string {

	//decodeString, err := hex.DecodeString(ct)
	//fmt.Println("decodeString: ")
	//if err != nil {
	//	fmt.Println("err: ", err)
	//}
	//cipher, err := aes.NewCipher(key)
	//fmt.Println("cipher: ", cipher)
	//if err != nil {
	//	fmt.Println("err: ", err)
	//}
	//pt := make([]byte, len(decodeString))
	//cipher.Decrypt(pt, decodeString)
	//s := string(pt[:])
	//fmt.Println("s: ", s)

	keyLenMap := map[int]struct{}{16: {}, 24: {}, 32: {}, 64: {}, 128: {}, 256: {}}
	if _, ok := keyLenMap[len(keyLenMap)]; !ok {
		log.Fatal("key长度必须是 16、14、32、64、128")
	}
	// 反解码base64
	decodeString, _ := base64.StdEncoding.DecodeString(ct)
	// 秘钥和待加密数据转成[]byte
	keyByte := []byte(key)
	// 创建密码组，长度只能是16、24、32字节
	block, _ := aes.NewCipher(keyByte)
	// 获取秘钥长度
	blockSize := block.BlockSize()
	decrypted := make([]byte, len(decodeString))
	for bs, be := 0, blockSize; bs < len(decodeString); bs, be = bs+blockSize, be+blockSize {
		block.Decrypt(decrypted[bs:be], decodeString[bs:be])
	}
	// 解码
	return string(PKCS7UNPadding(decrypted))
}

// 解码
func PKCS7UNPadding(originDataByte []byte) []byte {
	length := len(originDataByte)
	unpadding := int(originDataByte[length-1])
	return originDataByte[:(length - unpadding)]
}
